<template>
  <div>
    <Row :gutter="10">
      <Col>
      <Card>
        <Row class="live_wrapper clearfix">
          <Button type="primary"
                  style="float:right;width:90px;height: 34px;font-size: 14px;"
                  @click="addArticle">添加</Button>
          <Input v-model="filter.title"
                 @on-search="search"
                 search
                 enter-button="查询"
                 placeholder="请输入资讯标题"
                 style="width:290px; margin-right: 10px;float: right;top:0;font-size: 14px;" />
        </Row>
        <Row class="margin-top-10 table_pattern table_pattern2">
          <Table :loading="loading"
                 :columns="columns"
                 :data="list"></Table>
        </Row>
        <Row class="margin-top-10">
          <Page :total="pagenation.totalPage"
                :page-size="pagenation.perPage"
                :current="pagenation.currentPage"
                show-elevator
                show-total
                @on-change="change"></Page>
        </Row>
      </Card>
      </Col>
    </Row>
    <Modal v-model="edit"
           :title="title"
           width="900px"
           :mask-closable="false"
           class="goods_modal"
           :z-index='100'>
      <Form :model="formValidate"
            ref="formValidate"
            :label-width="100">
        <FormItem label="资讯标题"
                  prop="title"
                  class="label_required">
          <Input v-model="formValidate.title"
                 placeholder="请输入资讯标题"
                 style='width:60%' />
        </FormItem>
        <FormItem label="资讯封面"
                  prop="cover">
          <div>
            <Row type="flex"
                 justify="start"
                 align="middle"
                 class="height-100">
              <div style="display: block;text-align: center;">
                <Upload ref="upload"
                        :max-size="500"
                        :show-upload-list="false"
                        action="https://up.qiniup.com"
                        :on-format-error="handleFormatError"
                        :before-upload="handleBeforeUpload"
                        :on-progress="handleProgress"
                        :on-success="handleSuccess"
                        :on-error="handleError"
                        :data="{token:upload_token}">
                  <Button cover="ios-cloud-upload-outline">上传文件</Button>
                  <span style="padding-left:20px; color:#999">建议尺寸: 160*160px，JPG、PNG、JPEG格式，图片小于500KB</span>
                </Upload>
              </div>
            </Row>
            <Row class="margin-top-20">
              <div class=""
                   v-if="this.formValidate.cover">
                <template>
                  <div class="demo-upload-list">
                    <img :src="this.formValidate.cover"
                         style='width:150px; height:100px'>
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline"
                            @click.native="handleView(this.formValidate.cover)"></Icon>
                      <Icon type="ios-trash-outline"
                            @click.native="handleRemove()"></Icon>
                    </div>
                  </div>
                </template>
              </div>
            </Row>
          </div>
        </FormItem>
        <FormItem label="资讯分类"
                  prop="cate_id">
          <Select v-model="formValidate.cate_id"
                  style="width:200px">
            <Option v-for="(item, key) in cate_list"
                    :value="item.id"
                    :key="key">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="资讯来源"
                  prop="source"
                  class="label_required">
          <Input v-model="formValidate.source"
                 placeholder="请输入资讯来源"
                 style='width:60%' />
        </FormItem>
        <FormItem label="资讯内容"
                  prop="content"
                  class="label_required">
          <NEditor v-if="!spinShow"
                   :msg="formValidate.content"
                   @changeMsg="changeMsg"></NEditor>
        </FormItem>
        <FormItem>
          <Button :loading="saving"
                  type="primary"
                  @click="handleSubmit"
                  style="width: 90px;height: 35px;border-radius: 0;font-size: 14px;">提交</Button>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="visible"
           :title="title"
           width="500px"
           :mask-closable="false"
           class="goods_modal"
           :z-index='100'>
      <img :src="imgName">
    </Modal>
  </div>
</template>
<script>
import config from '@/config'
import { getQiniu, articleList, editArticle, changeArticleStatus, cateListForSelect } from '@/api/main'
export default {
  data () {
    return {
      upload_token: '',
      qiniu_url: '',
      visible: false,
      imgName: '',
      spinShow: false,
      pagenation: {},
      columns: [
        {
          key: 'title',
          title: '标题',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.title)
          },
        },
        {
          key: 'cover',
          title: '封面',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              {
                style: {
                  backgroundImage: 'url(' + params.row.cover + ')',
                  width: '100px',
                  height: '60px',
                  objectFit: 'cover',
                  margin: '10px auto',
                  position: 'relative',
                  cursor: 'pointer',
                  backgroundSize: 'cover',
                },
                on: {
                  click: e => {
                  },
                },
              }
            )
          },
        },
        {
          key: 'cate_name',
          title: '分类',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.cate_name)
          },
        },
        {
          key: 'source',
          title: '来源',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.source)
          },
        },
        {
          key: 'h5_url',
          title: 'h5地址',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.h5_url)
          },
        },
        {
          key: 'is_recom',
          title: '今日头号推荐',
          align: 'center',
          render: (h, params) => h('i-switch', {
            props: {
              value: params.row.is_recom,
              size: 'large',
              'true-value': 1,
              'false-value': 0
            },
            on: {
              'on-change': () => {
                this.changeArticleStatus(params.row, 2)
              }
            }
          }, [
            h('span', {
              slot: 'open',
              domProps: {
                innerHTML: '开启'
              }
            }),
            h('span', {
              slot: 'close',
              domProps: {
                innerHTML: '关闭'
              }
            })
          ]
          )
        },
        {
          key: 'article_recom',
          title: '资讯精选',
          align: 'center',
          render: (h, params) => h('i-switch', {
            props: {
              value: params.row.article_recom,
              size: 'large',
              'true-value': 1,
              'false-value': 0
            },
            on: {
              'on-change': () => {
                this.changeArticleStatus(params.row, 4)
              }
            }
          }, [
            h('span', {
              slot: 'open',
              domProps: {
                innerHTML: '开启'
              }
            }),
            h('span', {
              slot: 'close',
              domProps: {
                innerHTML: '关闭'
              }
            })
          ]
          )
        },
        {
          key: 'status',
          title: '状态',
          width: 150,
          align: 'center',
          render: (h, params) => h('i-switch', {
            props: {
              value: params.row.status,
              size: 'large',
              'true-value': 1,
              'false-value': 0
            },
            on: {
              'on-change': () => {
                this.changeArticleStatus(params.row, 1)
              }
            }
          }, [
            h('span', {
              slot: 'open',
              domProps: {
                innerHTML: '开启'
              }
            }),
            h('span', {
              slot: 'close',
              domProps: {
                innerHTML: '关闭'
              }
            })
          ]
          )
        },
        {
          key: 'created_time',
          title: '创建日期',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.created_time)
          },
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  style: {
                    marginRight: '5px',
                    border: 0,
                    background: 'transparent',
                    fontSize: '14px',
                    color: '#377EEF'
                  },
                  on: {
                    click: () => {
                      this.editArticle(params.row)
                    },
                  },
                },
                '编辑',
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除该资讯吗?',
                    transfer: true,
                  },
                  on: {
                    'on-ok': () => {
                      this.changeArticleStatus(params.row, 3)
                    },
                  },
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        border: 0,
                        background: 'transparent',
                        fontSize: '14px',
                        color: '#377EEF'
                      },
                      props: {
                        placement: 'top',
                        size: 'small',
                      },
                    },
                    '删除',
                  ),
                ],
              ),
            ])
          },
        },
      ],
      edit: false,
      title: '添加资讯',
      list: [],
      cate_list: [],
      loading: true,
      saving: false,
      formValidate: {
        id: 0,
        title: '',
        cover: '',
        content: '',
        source: '',
        cate_id: 0,
      },
      filter: {
        page: 0,
        title: '',
        cate_id: 0,
      },
    }
  },
  methods: {
    change: function (page) {
      this.loading = true
      this.filter.page = page - 1
      this.getArticleList()
    },
    search: function () {
      this.filter.page = 0
      this.getArticleList()
    },
    changeMsg (msg) {
      this.formValidate.content = msg
    },
    addArticle: function () {
      this.spinShow = true
      this.edit = true
      this.formValidate.id = 0
      this.formValidate.content = ''
      this.title = '添加资讯'
      this.handleReset('formValidate')
      setTimeout(() => {
        this.spinShow = false
      }, 1)
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    editArticle: function (obj) {
      this.spinShow = true
      this.formValidate = Object.assign({}, obj)
      this.title = '编辑资讯'
      this.edit = true
      setTimeout(() => {
        this.spinShow = false
      }, 1)
    },
    changeArticleStatus (item, type) {
      let obj = {}
      obj.id = item.id
      obj.type = type
      changeArticleStatus(obj).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.getArticleList()
        } else {
          this.$Message.error(res.text)
        }
      })
    },
    handleSubmit () {
      if (this.formValidate.title == '') {
        this.$Message.error("请输入资讯标题"); return;
      }
      if (this.formValidate.cover == '') {
        this.$Message.error("请上传资讯封面"); return;
      }
      if (this.formValidate.cate_id == 0) {
        this.$Message.error("请选择资讯分类"); return;
      }
      if (this.formValidate.source == '') {
        //this.$Message.error("请输入资讯来源");return;
      }
      if (this.formValidate.content == '') {
        this.$Message.error("请输入资讯内容"); return;
      }
      editArticle(this.formValidate).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.edit = false
          this.getArticleList()
        } else {
          this.$Message.error(res.text)
        }
      })
    },
    handleFormatError (file) {
      this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
    },
    handleBeforeUpload (file) {
      if (file.size > 500 * 1024) {
        this.$Message.error("图片大小不能超过500KB");
        return;
      }
    },
    handleProgress (event, file) { },
    handleSuccess (event, file, fileList) {
      this.formValidate.cover = file.response.domain + file.response.key
    },
    handleError (event, file) { },
    handleView (img_url) {
      this.imgName = img_url
      this.visible = true
    },
    handleRemove () {
      this.formValidate.cover = '';
    },
    getArticleList () {
      articleList(this.filter).then(res => {
        if (res.code == 0) {
          this.list = res.data
          this.loading = false
          this.pagenation.currentPage = parseInt(res.currentPage) + 1
          this.pagenation.totalPage = parseInt(res.totalPage)
          this.pagenation.perPage = parseInt(res.perPage)
        }
      })
    },
    async init () {
      let qiniu = await getQiniu()
      this.upload_token = qiniu.token
      this.qiniu_url = qiniu.url
    }
  },
  mounted () {
    this.init();
    this.getArticleList()
    cateListForSelect().then(res => {
      if (res.code == 0) {
        this.cate_list = res.data
      }
    })
  }
}
</script>
